#!/usr/bin/python3
from lanzou.api import LanZouCloud
import os
"""
上传蓝奏云，开代理大概会NG 9，网络错误
"""

def get_result(code):
    if code == LanZouCloud.SUCCESS:
        return 'OK'
    else:
        return f'NG errorCode:{code}'


def login(ylogin, phpdisk_info):
    print('开始登入')
    cookie = {'ylogin': ylogin, 'phpdisk_info': phpdisk_info}
    code = lzy.login_by_cookie(cookie)
    print('登入结果:', get_result(code))
    return code


def show_progress(file_name, total_size, now_size):
    percent = now_size / total_size
    bar_len = 60  # 进度条长总度
    bar_str = '>' * round(bar_len * percent) + '=' * round(bar_len * (1 - percent))
    print('\r{:.2f}%\t[{}] {:.1f}/{:.1f}MB '.format(
        percent * 100, bar_str, now_size / 1048576, total_size / 1048576), end='')


def handler(fid, is_file):
    if is_file:
        code = lzy.set_desc(fid, description, is_file=True)
        print('描述信息设置结果:', get_result(code))


def upload(path, id):
    print('开始上传文件')
    code = lzy.upload_file(path, id, callback=show_progress, uploaded_handler=handler)
    print('文件上传结果:', get_result(code))
    return code


def upload_fromdir(dir, folder_id, rewrite):
    list = lzy.get_file_list(folder_id)
    for p in os.listdir(dir):
        file_path = os.path.join(dir, p)
        if os.path.isfile(file_path):
            if list.find_by_name(os.path.basename(file_path)) is None or \
               (list.find_by_name(os.path.basename(file_path)) is not None and not rewrite):
                print("开始上传{}".format(file_path))
                if upload(file_path, folder_id) == LanZouCloud.SUCCESS:
                    print('{} uploaded.'.format(file_path))
                else:
                    print('{} upload failed.'.format(file_path))
            else:
                print("Duplicate file {}, skipped.".format(p))
        else:
            folder_id = lzy.mkdir(folder_id, os.path.basename(file_path), os.path.basename(file_path))
            lzy.set_passwd(folder_id, '', False)
            upload_fromdir(file_path, folder_id, rewrite)


lzy = LanZouCloud()
# 得放外面，每个文件的描述
description = "share"
if __name__ == "__main__":
    # 登录蓝奏云后查看cookie，3天有效期
    # LANZOU_ID ： woozooo.com -> Cookie -> ylogin
    # LANZOU_PSD ： pc.woozooo.com -> Cookie -> phpdisk_info
    LANZOU_ID = ""
    LANZOU_PSD = ""
    # 蓝奏云文件夹名称，会自动创建
    LANZOU_FOLDER = "阅读test"
    # 本地上传文件夹路径，包括子文件夹，递归上传，自动创建文件夹
    UPLOAD_FOLDER = os.path.join(os.getcwd(), "阅读大礼包")
    # 是否覆写已存在的文件
    rewrite = False
    if not LANZOU_ID:
        LANZOU_ID = os.environ["LANZOU_ID"] 
    if not LANZOU_PSD:
        LANZOU_PSD = os.environ["LANZOU_PSD"] 
    if login(LANZOU_ID, LANZOU_PSD) == LanZouCloud.SUCCESS:
        print('文件夹名字:', LANZOU_FOLDER)
        folders = lzy.get_move_folders()
        folder_id = folders.find_by_name(LANZOU_FOLDER)
        if folder_id is None:
            folder_id = lzy.mkdir(-1, os.path.basename(LANZOU_FOLDER), os.path.basename(LANZOU_FOLDER))
        print('文件夹ID:', folder_id)
        print('上传文件路径:', UPLOAD_FOLDER)
        upload_fromdir(UPLOAD_FOLDER, folder_id, rewrite)
        info = lzy.get_share_info(folder_id, is_file=False)
        print('\n分享链接:{}\n提取码:{}'.format(info.url, '无' if info.pwd == '' else info.pwd))

